#!/usr/bin/ruby

require 'active_record'

# Test using ActiveRecord

limit = 300

print 'Connecting to the database...'
ActiveRecord::Base.establish_connection(
	:adapter => 'sqlite3',
	:database => 'test.db'
)
class TestData < ActiveRecord::Base
	attr_accessible :id, :value, :units
  set_table_name "data"
end
TestData.delete_all
puts ' Connection established!'

print 'Generating random input data... '

n = rand(limit)
used_ids = []
input = File.open('input','w+')
input.puts n

# Generate random data
n.times do
	
	# Put random data in file
	x = rand(limit)
	while used_ids.include?(x) do
		x = rand(limit)
	end
	exit unless TestData.find_by_id(x).nil?
	used_ids << x
	y = rand(limit)
	z = rand(limit)
	input.puts [x,y,z].join(' ')
	
	# Put random data in database
	data = TestData.new do |t|
		t.id = x
		t.value = y
		t.units = z
	end
	data.save

end

# Operators
vmin = rand(4) == 0 ? '_' : rand(limit)
vmax = rand(4) == 0 ? '_' : rand(limit)
if vmin != '_' and vmax != '_' and vmin > vmax
	aux = vmin
	vmin = vmax
	vmax = aux
end
nmin = rand(4) == 0 ? '_' : rand(limit)
nmax = rand(4) == 0 ? '_' : rand(limit)
if nmin != '_' and nmax != '_' and nmin > nmax
	aux = nmin
	nmin = nmax
	nmax = aux
end
ops = ['&','|']
op = ops[rand(2)] 
input.puts [vmin,vmax,op,nmin,nmax].join(' ')
puts "#{n} lines of data generated in input and #{TestData.count} lines recorded in database"
input.close

# Output

output = File.open('output','w+')

print 'Generating output... '

sql1 = ""
sql1 += "value >= #{vmin}" unless vmin == '_'
sql1 += " AND " if vmin != '_' and vmax != '_'
sql1 += "value <= #{vmax}" unless vmax == '_'

sql2 = ""
sql2 += "units >= #{nmin}" unless nmin == '_'
sql2 += " AND " if nmin != '_' and nmax != '_'
sql2 += "units <= #{nmax}" unless nmax == '_'

middle = op == '|' ? " OR " : " AND "
sql1 = "1 == 1" if sql1 == ""
sql2 = "1 == 1" if sql2 == ""
sql = "(#{sql1}) #{middle} (#{sql2})"

TestData.find(:all, :order => 'id ASC', :conditions => sql).each do |t|
	output.puts [t.id,t.value,t.units].join(' ')
end

puts 'Output generated'
output.close
